package work.droit.data.search;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import work.droit.data.Champs.DefinitionChamp;
import work.droit.data.Definition;
import work.droit.gui.ApiController;
import work.util.data.io.ManipFile;
import work.util.data.table.Tables.Record;

public class DefinitionSearch
{
	private Map<Integer, String>	cacheDefinition	= null;

	public DefinitionSearch()
	{
		cacheDefinition = new HashMap<Integer, String>();
	}

	public List<Definition> findDefinitions(String searchPattern)
	{
		Definition definitionTmp = new Definition();
		definitionTmp.setChamp(Definition.mot, "");
		List<Record<DefinitionChamp>> fiches = definitionTmp.searchListRecords(Definition.mot, Definition.mot);

		List<Definition> definitionFound = new ArrayList<Definition>();

		for (Record<DefinitionChamp> rec : fiches)
		{
			Definition definition = (Definition) rec;
			String name = (String) definition.getValue(Definition.mot);

			if (name.contains(searchPattern))
			{
				definitionFound.add(definition);
				continue;
			}
			if (findInContent(definition, searchPattern))
			{
				definitionFound.add(definition);
				continue;
			}
		}

		return definitionFound;
	}

	private boolean findInContent(Definition definition, String searchPattern)
	{
		Integer id = (Integer) definition.getValue(Definition.id);
		String content = cacheDefinition.get(id);
		if (content == null)
		{
			content = ManipFile.getContent(ApiController.pathDocument + id + "d.txt");
			cacheDefinition.put(id, content);
		}
		if (content.contains(searchPattern))
			return true;
		return false;
	}
}
